const app = getApp();
let liveroom = require('../../../utils/liveroom.js');
let getlogininfo = require('../../../getlogininfo.js');
let listIntval = null;
const { config } = require('../../../../common/utils/ws/ws-config.js');
const {
  getUserInfo,
  getUserInfoWidthCredentials,
  getOpenID,
} = require('../../../../common/utils/ws/wsxcx-opendata-sdk');
Page({
  data: {
    roomName: '', // 房间名称
    // userName: '', // 用户名称
    roomList: [], // 房间列表
    isGetLoginInfo: false, // 是否已经获取登录信息
    firstshow: true, // 第一次显示页面
    tapTime: '', // 防止两次点击操作间隔太快
    isAdmin: 0, // 默认是游客身份
    isShow: false,
    isShowPwdModel: false,  
    isSetting: false, // 验证配置
    isServer: false, // 验证服务
    roomPassWord: '',  //房间密码
    roomID: '',  //房间id
    pwdCorrect: false, //密码是否正确
    floatItems: [{
      type: 0, // 自定义事件
      show: true,
      iconClass: 'icon icon-jia',
      event: 'myEvent1',
    }, {
      type: 0, // 自定义事件
      show: true,
      iconClass: 'icon icon-zaixianketang',
      event: 'myEvent2',
    }],
  },
  onLoad() {
    // 测试直播配置
    this.checkImSetting();
  },
  onReady() {
    wx.showLoading({
      title: '登录信息获取中',
    });
    getlogininfo.getLoginInfo({
      type: 'live_room',
      success: ret => {
        this.setData({
          firstshow: false,
          isGetLoginInfo: true,
        });
        this.getRoomList();
        wx.hideLoading();
      },
      fail: ret => {
        this.setData({
          isGetLoginInfo: false,
        });
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: ret.errMsg,
          showCancel: false,
          complete: function () {
            wx.navigateBack({});
          },
        });
      },
    });
  },
  onShow(){
    let { isSetting, isServer } = this.data;
    if(isSetting && isServer){
    listIntval = setInterval(() => {
      if (this.data.isGetLoginInfo) {
        this.getRoomList();
        this.checkIdentity();
        this.checkAuthorize();
      }
    }, 5000);
    }
  },
  onHide(){
    console.log('roomlist onHide');
    clearInterval(listIntval);
  },
  onUnload() {
    console.log('roomlist onHide');
    clearInterval(listIntval);
    liveroom.logout();
  },
  onPullDownRefresh() {
    this.getRoomList();
    this.checkIdentity();
    this.checkAuthorize();
    wx.stopPullDownRefresh();
  },

  // 测试配置
  checkImSetting(){
    app.util.request({
      url:'entry/wxapp/index',
      data:{
        op:'checkImSetting',
        uniacid: `${config.uniacid}`
      },
      module:'cm_trtc',
      success: res=>{
        let { errno, data:{msg: errMsg} } = res.data;
        if(errno) {
          wx.showModal({
            title: '提示',
            content: errMsg,
            showCancel: false,
            success: res =>{
              wx.navigateBack({});
            }
          })
          return;
        } else {
          this.setData({
            isSetting: true
          })
          // 测试直播服务
          this.checkNode();
        }
      }
    })
  },
  // 测试直播服务是否开启
  checkNode(){
    app.util.request({
      url:'entry/wxapp/index',
      data:{
        op:'checkNode',
        uniacid: `${config.uniacid}`
      },
      module:'cm_trtc',
      success: res=>{
        let { errno, data:{msg: errMsg} } = res.data;
        if(errno) {
          wx.showModal({
            title: '提示',
            content: errMsg,
            showCancel: false,
            success: res =>{
              wx.navigateBack({});
            }
          })
          return;
        } else {
          this.setData({
            isServer: true
          })
          this.onShow();
          this.checkIdentity();
          this.checkAuthorize();
        }
      }
    })
  },
  getRoomList() {
    let self = this;
    if (!self.data.isGetLoginInfo) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    liveroom.getRoomList({
      data: {
        index: 0,
        cnt: 20,
      },
      success: function (ret) {
        const rooms = ret.rooms;
        for (let i = 0; i < rooms.length; i++) {
          const room = rooms[i];
          const roomInfo = JSON.parse(room.roomInfo || '{}');
          room.roomName = roomInfo.roomName;
          room.pureAudio = roomInfo.pureAudio;
        }
        self.setData({
          roomList: rooms,
        });
        console.log('获取房间列表成功');
      },
      fail: function (ret) {
        console.log(ret);
        wx.showModal({
          title: '获取房间列表失败',
          content: ret.errMsg,
          showCancel: false,
        });
      },
    });
  },
  goRoom(e) {
    let { pwdCorrect } = this.data;
    let roomInfo = e&&e.currentTarget&&e.currentTarget.dataset||this.data.roomInfo;
    this.setData({roomInfo});
    this.checkPwdExists().then(needPwd => {
      if (needPwd && !pwdCorrect) {  //需要密码&&不正确  
        return;
      }
      this.closePwdModal();
    let nickName = wx.getStorageSync('wsUserInfo') && wx.getStorageSync('wsUserInfo').nickName;
    let nowTime = new Date();
    if (nowTime - this.data.tapTime < 1000) {
      return;
    }
      let url = `../room/room?roomID=${roomInfo.roomid}&roomName=${roomInfo.roomname}&pureAudio=${roomInfo.pureaudio}&userName=${nickName}&accelerateURL=${roomInfo.accelerateurl}`;
    wx.navigateTo({
      url: url,
    });
    wx.showToast({
      title: '进入房间',
        icon: 'none',
      duration: 1000,
    });
    this.setData({
      tapTime: nowTime,
      pwdCorrect:!pwdCorrect,
    });
    });
  },
  goCreateRoom() {
    if (!this.data.isGetLoginInfo) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    wx.navigateTo({
      url: `/cm_trtc_1/pages/live-phone/roomcreate/roomcreate`,
    });
  },
  checkIdentity() {  // 检查身份 0:游客 1:管理员
    getOpenID().then(openid => {
      app.util.request({
        url: 'entry/wxapp/index',
      data: {
        op: 'checkAdmin',
          openid,
      },
        module: 'cm_trtc',
      success: res => {
        let isAdmin = res.data.data && res.data.data.is_admin||0;
          let { floatItems } = this.data;
          floatItems[0].show = isAdmin ? true : false;
        this.setData({
          isAdmin:Number(isAdmin),
            floatItems,
        });
        app.globalData.isAdmin= Number(isAdmin);
      },
      fail: res => { // 如果后台返回错误 默认游客身份
          let { floatItems } = this.data;
          floatItems[0].show = false;
        this.setData({
          isAdmin: 0,
            floatItems,
        });
        app.globalData.isAdmin= 0;
      },
    });
    });
  },
  checkAuthorize() { // 检查用户是否已授权 为了后台能拿到头像昵称，这里需要强制授权一次
    getUserInfo().then(res => {}).catch(res => {
      this.setData({
        isShow: true,
      });
    });
  },
  getUserInfoWidthCredentials(e) {
    this.setData({
      isShow: !this.data.isShow,
    });
    getUserInfoWidthCredentials({
      url: 'auth/session/userinfo',
      method: 'POST',
      detail: e.detail,
      cachetime: 0,
    }).then(res => {
      getUserInfo().then(wsUserInfo => {
        liveroom.setUserName(wsUserInfo.nickName);  // 修改用户名
      });
    });
  },
  checkPwdExists() {  // 当前房间是否设置密码
    const { roomid } = this.data.roomInfo;
    this.checkConnectStatus();
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'checkPwdExists',
          roomid,
        },
        module: 'cm_trtc',
        success: res => {  //1：需要密码,0：不需要
          if (res.data && res.data.errno == 1) {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000,
            });
            return reject(res.data.message);
          }
          if (res.data.data && res.data.data.need_pwd) {
            this.setData({
              isShowPwdModel: true,
            });
            resolve(true);
          } else {
            resolve(false);
          }
        },
        fail: res => {
          resolve(false);
        },
      });
    });

  },
  checkRoomPwd() {  // 密码是否输入正确
    const { roomInfo: { roomid }, roomPassWord: password,pwdCorrect } = this.data;
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkRoomPwd',
        roomid,
        password,
      },
      module: 'cm_trtc',
      success: res => {
        wx.showToast({
          title: '密码输入正确',
          icon: 'none',
          duration: 2000,
        });
        this.setData({
          pwdCorrect: !pwdCorrect,
        });
        this.goRoom();
      },
      fail: res => {
        wx.showToast({
          title: '密码输入错误',
          icon: 'none',
          duration: 2000,
        });
      },
    });
  },
  bindRoomPassWord(e) {
    this.setData({
      roomPassWord: e.detail.value,
    });
  },
  closePwdModal(){
    this.setData({
      isShowPwdModel: false,
    });
  },
  checkConnectStatus(){
    const { roomid } = this.data.roomInfo;
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkRoomConnect',
        roomid,
      },
      module: 'cm_trtc',
      success: res => {
        let connectStatus = res.data.data && res.data.data.connect_status||0;
        app.globalData.connectStatus = Number(connectStatus) ;
      },
      fail: res => {
        app.globalData.connectStatus = 0;
      },
    });
  },
  toLiveHistory() {
    app.util.navigateTo('cm_trtc_1/pages/live-phone/live-history/live-hisrory');
  },
});
